import { YkBabylonScene } from './create3D.ts'
import { storeToRefs } from 'pinia'
import { useSgesMAStore } from './MountainGesCalA.ts'
import { AbstractMesh, PhysicsMotionType, Vector3 } from '@babylonjs/core'

const store = useSgesMAStore()
const {
  velBlock,
  numRails,
  totalBlocksNum
} = storeToRefs(store)

export const startCharging = (ykScene: YkBabylonScene, simNum: number = 1) => {
  // 1.找到最靠近斜坡的重物小车
  // 查找方法：遍历所有小车
  console.log('开始充电')
  const railZs = ykScene.customData.railZs!.slice(0, simNum)
  const maxCartNum = Math.ceil(totalBlocksNum.value / numRails.value)

  // 存储需要持续施加力的小车列表
  const cartsToCharge: {cart: AbstractMesh, z: number, wheels: {wheel: AbstractMesh, z: number}[]}[] = []

  for (let [idx, z] of railZs.entries()) {
    let cart: AbstractMesh | null = null
    const wheels: {wheel: AbstractMesh, z: number}[] = []
    for (let i = maxCartNum - 1; i > 0; i--) {
      cart = ykScene.scene.getMeshByName(`Cart_${idx + 1}_${i}`)
      cart?.unfreezeWorldMatrix()
      cart?.physicsBody?.setMotionType(PhysicsMotionType.DYNAMIC)
      for (let j of [0, 1, 2, 3]) {
        const wheel = ykScene.scene.getMeshByName(`Cart_${idx + 1}_${i}_wheel${j}`)
        wheel?.physicsBody?.setMotionType(PhysicsMotionType.DYNAMIC)
        wheel?.unfreezeWorldMatrix()
        if (wheel) {
          wheels.push({wheel, z: wheel.position.z})
        }
      }
      if (cart?.position.x! < 0) {
        break
      }
    }
    // 2.给该小车添加一个恒定的力，使其加速
    // 将需要充电的小车添加到列表中
    if (cart) {
      cartsToCharge.push({cart, z, wheels})
    }
  }

  // 3.检查小车速度是否达到额定速度
  // 2.创建一个渲染观察者来持续施加力
ykScene.scene.onBeforeRenderObservable.add(() => {
    // 对每个需要充电的小车施加力
    for (const cartInfo of cartsToCharge) {
      const {cart, z, wheels} = cartInfo;
      // 检查小车是否仍在场景中且有物理体
      if (cart && cart.physicsBody) {
        // 固定z轴位置，防止偏移
        const position = cart.position.clone();
        position.z = z;
        cart.position = position;

        // 同时固定四个轮子的z轴位置
        wheels.forEach(wheelInfo => {
          if (wheelInfo.wheel) {
            const wheelPosition = wheelInfo.wheel.position.clone();
            wheelPosition.z = wheelInfo.z;
            wheelInfo.wheel.position = wheelPosition;
          }
        });

        // 可选：检查小车速度是否达到额定速度，如果达到则停止施加力
        // const velocity = cart.physicsBody.getLinearVelocity()
        cart.physicsBody.setLinearVelocity(new Vector3(10, 0, 0))
        // if (velocity && velocity.length() < velBlock.value) {
        //   // 持续施加力
        //   cart.physicsBody.applyForce(new Vector3(648000, 0, 0), new Vector3(0, 0, 0))
        // }
      }
    }
  })

}
